package keter.mongo;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import keter.framework.AbstractBaseConfig;
import keter.framework.util.PropertiesUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import com.jfinal.ext.plugin.monogodb.MongodbPlugin;
//import javax.servlet.http.HttpServlet;
import com.jfinal.kit.PropKit;


/**
 * <p>Class       : keter.mongo.KeterMongoConfig
 * <p>Descdription: 同时支持JDBC和Mongodb数据源
 * @author  顾力行-gulixing@msn.com
 * @version 1.0.0
 */
public abstract class KeterMongoConfig extends AbstractBaseConfig{
    
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(AbstractBaseConfig.class);
    
    public static MongodbPlugin mongodb;
    public static final String MONGO_CONFIG_URL = "classpath:keter-mongo.properties";
    public static boolean initJDBC;
    private static String kUrl = KETER_CONFIG_URL;
    public KeterMongoConfig(){
        logger.info("初始化配置文件...");
        String mUrl = StringUtils.isEmpty(getMongoConfigUrl())?MONGO_CONFIG_URL:getMongoConfigUrl();
        //FIXME:多配置共存
        //        kUrl = StringUtils.isEmpty()?KETER_CONFIG_URL:getKeterConfigUrl();
        PropertiesUtil pl = new PropertiesUtil(kUrl,mUrl);
        //判断是否启用jdbc
        if(pl.contains("db.url")||pl.contains("db.test.url")){
            initJDBC = true;
        }
    }

    /**
     * <p>Method ：init
     * <p>Description : servlet启动时执行该方法
     *
     * @param config
     * @throws ServletException 
     * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
     */
    public void  init(ServletConfig config) throws ServletException{
        initMongo();
        if(!exists(kUrl)){
            logger.info("未发现keter配置文件，将不进行keter配置初始化。");
            return;
        }
        else if(initJDBC){
            super.initAll();
        }       
        else{
            logger.info("未发现jdbc数据源，将不进行关系型数据库初始化。");
            super.initCache();
        }
    }

    public void initMongo() {
        mongodb = new KeterMongoPlugin(
        		PropKit.get("mongo.host"),
        		PropKit.get("mongo.db")
                );
        if(!mongodb.start()) mongodb.start();
    }
    
    
    protected boolean exists(String location){
        Resource resource = new DefaultResourceLoader().getResource(location);
        return resource.exists();
    }
    
    public abstract String getMongoConfigUrl();
}
